package cn.zuo.service;

import cn.zuo.pojo.Message;
import cn.zuo.utils.PublicKeyPool;
import cn.zuo.utils.TalkingPool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import javax.swing.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.util.*;
/**
 * @Author 白白旧维
 * @Date 2021/7/7 11:13
 */
public class Talking extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(Talking.class);//得到logger变量
    private Socket s;
    private String sender;

    public void setSender(String sender) {
        this.sender = sender;
    }

    public Talking(Socket s){
        this.s = s;
    }

    public Socket getS() {
        return s;
    }

    @Override
    public void run() {

        while(true){
            ObjectInputStream ois = null;
            ObjectOutputStream oos = null;
            Message msg = null;
            try {
                //获取sender的信息
                ois = new ObjectInputStream(s.getInputStream());
                msg = (Message) ois.readObject();


                //新：服务端保存客户端登录时发送的的CtoC公钥
                if("key".equals(msg.getStatus())){
                    //新：也就是更新了公钥库，需要发送给所有登录用户这个公钥库中的更新信息 //我觉得这里有问题！！
                    //d、服务端更新的CtoC公钥发送所有登录客户端是否成功？？？
                    System.out.println("服务端更新的CtoC公钥发送所有登录客户端");
                    HashMap<String, Talking> all_login_talking = TalkingPool.getMap();//所有登录用户
                    Set<String> all_login_talking_key = all_login_talking.keySet();
                    for (String key :
                            all_login_talking_key) {
                        if(msg.getSender().equals(key)){
                            continue;
                        }
                        ObjectOutputStream oos_update_key = new ObjectOutputStream(all_login_talking.get(key).getS().getOutputStream());
                        oos_update_key.writeObject(msg);
                        System.out.print("("+key+":"+msg+") ");
                    }
                    System.out.println();
                    System.out.println();



                    BigInteger e = new BigInteger(msg.getMsg().split("_")[0]);
                    BigInteger n = new BigInteger(msg.getMsg().split("_")[1]);

                    PublicKeyPool.setClientKey_e(msg.getSender(),e);
                    PublicKeyPool.setClientKey_n(msg.getSender(),n);


                    System.out.println("服务端保存CtoC公钥！！");
                    Map<String, BigInteger> key_e = PublicKeyPool.getClient_key_e();//b、服务端保存CtoC公钥是否成功？？
                    Map<String, BigInteger> key_n = PublicKeyPool.getClient_key_n();
                    Set<String> all_key_key = key_e.keySet();
                    for (String key :
                            all_key_key) {
                        System.out.print(key+" : e("+key_e.get(key)+")"+",n("+key_n.get(key)+")  ");
                    }
                    System.out.println();
                    System.out.println();


                    continue;//不能使用return
                }


                //发送信息给getter
                Talking talking = TalkingPool.getTalking(msg.getReceiver());
                if(talking==null){
                    System.out.println("talking is null");

                }else{
                    System.out.println(msg.getSender()+"给"+msg.getReceiver()+"发送："+msg.getMsg());
                    System.out.println("状态："+msg.getStatus());
                    System.out.println();
                    System.out.println();
                    logger.info(msg.getSender()+"给"+msg.getReceiver()+"发送："+msg.getMsg());

                    oos = new ObjectOutputStream(talking.getS().getOutputStream());
                    oos.writeObject(msg);
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                PublicKeyPool.removeClientKey_e(sender);
                System.out.println("移除["+sender+"]的ClientKey_e");
                logger.info("移除["+sender+"]的ClientKey_e");
                PublicKeyPool.removeClientKey_n(sender);
                System.out.println("移除["+sender+"]的ClientKey_n");
                logger.info("移除["+sender+"]的ClientKey_n");
                TalkingPool.removeTalking(sender);
                System.out.println("移除["+sender+"]的talking缓存");
                logger.info("移除["+sender+"]的talking缓存");
//                e.printStackTrace();
                break;
            }
        }



    }

}
